package com.zcn.io.web.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zcn.io.common.entity.TransferPhone;
import com.zcn.io.common.exception.ServiceException;
import com.zcn.io.common.util.CollectionUtils;
import com.zcn.io.web.api.dto.DictDto;
import com.zcn.io.web.api.query.OrderMainQuery;
import com.zcn.io.web.api.vo.CardNameVo;
import com.zcn.io.web.api.vo.PhoneCardVo;
import com.zcn.io.web.api.vo.TransferPhoneVo;
import com.zcn.io.web.api.vo.phoneCard.NegotiationPhoneCardVo;
import com.zcn.io.web.api.vo.phoneCard.TrusteeshipPhoneCardVo;
import com.zcn.io.web.mapper.TransferPhoneMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: 202438 邱建伟
 * @date: 2024/9/27 12:31
 * @Copyright (c) 2024, 江苏金恒信息科技股份有限公司
 */
@Service
public class TransferPhoneService {

    @Autowired
    private TransferPhoneMapper transferPhoneMapper;

    public List<TransferPhoneVo> list(TransferPhone transferPhone) {
        return this.transferPhoneMapper.list(transferPhone);
    }

    public void save(TransferPhone transferPhone) {
        LambdaQueryWrapper<TransferPhone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TransferPhone::getPhoneNo, transferPhone.getPhoneNo());
        queryWrapper.or().eq(TransferPhone::getIndexId, transferPhone.getIndexId());
        queryWrapper.or().eq(TransferPhone::getOrderNumber, transferPhone.getOrderNumber());
        List<TransferPhone> transferPhones = this.transferPhoneMapper.selectList(queryWrapper);
        if (transferPhones.size() > 0) {
            throw new ServiceException(600, "该号码已存在!");
        }
        transferPhoneMapper.insert(transferPhone);
    }

    public void update(TransferPhone transferPhone) {
        LambdaQueryWrapper<TransferPhone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(TransferPhone::getId, transferPhone.getId());
        queryWrapper.nested(w -> {
            w.eq(TransferPhone::getPhoneNo, transferPhone.getPhoneNo());
            w.or().eq(TransferPhone::getIndexId, transferPhone.getIndexId());
            w.or().eq(TransferPhone::getOrderNumber, transferPhone.getOrderNumber());
        });
        List<TransferPhone> transferPhones = this.transferPhoneMapper.selectList(queryWrapper);
        if (transferPhones.size() > 0) {
            throw new ServiceException(600, "该号码已存在!");
        }
        transferPhoneMapper.updateById(transferPhone);
    }

    public void delete(String id) {
        transferPhoneMapper.deleteById(id);
    }

    public TransferPhone getById(String id) {
        return transferPhoneMapper.selectById(id);
    }

    public List<DictDto> dict() {
        return transferPhoneMapper.dict();
    }

    public List<PhoneCardVo> getPhoneCardList(OrderMainQuery orderMain) {
        //拉取所有手机号
        List<TransferPhone> activePhoneList = transferPhoneMapper.listAllActivePhone();
        //拉取所有的有效的托管订单
        List<TrusteeshipPhoneCardVo> trusteeshipPhoneCardVos = transferPhoneMapper.listAllActiveTrusteeship();
        Map<String, List<TrusteeshipPhoneCardVo>> trusteeshipGroup = CollectionUtils.groupBy(trusteeshipPhoneCardVos, TrusteeshipPhoneCardVo::getPhoneCode);
        //拉取所有有效的的协商任务
        List<NegotiationPhoneCardVo> negotiationPhoneCardVos = transferPhoneMapper.listAllActiveNegotiation();
        Map<String, List<NegotiationPhoneCardVo>> negotiationGroup = CollectionUtils.groupBy(negotiationPhoneCardVos, NegotiationPhoneCardVo::getPhoneCode);
        //创建最终返回结果
        List<PhoneCardVo> results = new ArrayList<>();
        for (TransferPhone transferPhone : activePhoneList) {
            PhoneCardVo phoneCardVo = new PhoneCardVo();
            phoneCardVo.setPhoneCode(transferPhone.getIndexId());
            phoneCardVo.setPhoneNo(transferPhone.getPhoneNo());
            phoneCardVo.setPhoneNoColor(transferPhone.getPhoneNoColor());
            phoneCardVo.setPhoneCodeColor(transferPhone.getIndexIdColor());
            phoneCardVo.setOrderNumber(transferPhone.getOrderNumber());
            phoneCardVo.setTrusteeship(
                    trusteeshipGroup.getOrDefault(transferPhone.getIndexId(), new ArrayList<>()).stream().map(TrusteeshipPhoneCardVo::getCustomName).collect(Collectors.toList())
            );
            phoneCardVo.setNegotiation(
                    negotiationGroup.getOrDefault(transferPhone.getIndexId(), new ArrayList<>()).stream().map(NegotiationPhoneCardVo::getCustomName).collect(Collectors.toList())
            );
            if (CollectionUtil.isNotEmpty(phoneCardVo.getTrusteeship()) || CollectionUtil.isNotEmpty(phoneCardVo.getNegotiation())){
                results.add(phoneCardVo);
            }
        }
        return results;
    }

    /**
     * @desc: 待处理卡贴生成
     * @author 202438 邱建伟
     * @date 2025/3/23 16:04
     */
    public List<PhoneCardVo> getPhoneCardListWarn(OrderMainQuery orderMain) {
        orderMain.setOrderNoStart("0");
        orderMain.setOrderNoEnd("1");
        return getPhoneCardListBase(orderMain);
    }



    public List<PhoneCardVo> getPhoneCardListPlus(OrderMainQuery orderMain){
        List<PhoneCardVo> phoneCardList = this.transferPhoneMapper.getPhoneCardListPlus(orderMain);
        if (CollectionUtil.isEmpty(phoneCardList)) {
            return ListUtil.empty();
        }
        //根据手机编码进行分组
        Map<String, List<PhoneCardVo>> phoneGroup =
                phoneCardList.stream().collect(Collectors.groupingBy(PhoneCardVo::getPhoneCode));
        List<PhoneCardVo> results = new ArrayList<>();
        for (Map.Entry<String, List<PhoneCardVo>> entry : phoneGroup.entrySet()) {
            //根据业务类型进行分组
            Map<String, List<String>> businessGroup = entry.getValue().stream()
                    .peek(item->{
                        if (StrUtil.isEmpty(item.getBusinessType())){
                            item.setBusinessType("其他");
                        }
                        if (StrUtil.contains(item.getBusinessType(),"托管")){
                            item.setBusinessType("托管");
                        }
                    })
                    .collect(Collectors.groupingBy(
                            PhoneCardVo::getBusinessType,
                            Collectors.mapping(PhoneCardVo::getCustomName, Collectors.toList())
                    ));
            PhoneCardVo phoneCardVo = new PhoneCardVo();
            phoneCardVo.setPhoneCode(entry.getKey());
            if (CollectionUtil.isNotEmpty(entry.getValue())) {
                phoneCardVo.setPhoneCodeColor(CollectionUtil.getFirst(entry.getValue()).getPhoneCodeColor());
                phoneCardVo.setOrderNumber(CollectionUtil.getFirst(entry.getValue()).getOrderNumber());
                phoneCardVo.setPhoneNo(CollectionUtil.getFirst(entry.getValue()).getPhoneNo());
                phoneCardVo.setPhoneNoColor(CollectionUtil.getFirst(entry.getValue()).getPhoneNoColor());
                List<CardNameVo> cardNameVoList = new ArrayList<>();
                List<String> nameList = entry.getValue().stream().map(PhoneCardVo::getCustomName)
                        .distinct()
                        .sorted(Comparator.comparingInt(String::length))
                        .collect(Collectors.toList());
                for (String s : nameList) {
                    CardNameVo cardNameVo = new CardNameVo();
                    cardNameVo.setName(s);
                    if (businessGroup.getOrDefault("托管",new ArrayList<>()).contains(s)){
                        cardNameVo.setColor("#F1FC12");
                    }
//                    if (businessGroup.getOrDefault("托管",new ArrayList<>()).contains(s)&&
//                            businessGroup.getOrDefault("协商",new ArrayList<>()).contains(s)){
//                        cardNameVo.setColor("##F1613D");
//                    }else if (businessGroup.getOrDefault("托管",new ArrayList<>()).contains(s)){
//                        cardNameVo.setColor("#F1FC12");
//                    }else if (businessGroup.getOrDefault("协商",new ArrayList<>()).contains(s)){
//                        cardNameVo.setColor("#7CF449");
//                    }
                    cardNameVoList.add(cardNameVo);
                }
                phoneCardVo.setNameVoList(cardNameVoList);
            }
            results.add(phoneCardVo);
        }
        //对List进行排序,根据对象中的orderNumber字段进行排序.
        results.sort(Comparator.comparingDouble(o ->
                {
                    if (StrUtil.isEmpty(o.getOrderNumber())){
                        return Double.MAX_VALUE;
                    }else{
                        return Double.parseDouble(o.getOrderNumber());
                    }
                }
        ));
        return results;
    }



    public List<PhoneCardVo> getPhoneCardListBase(OrderMainQuery orderMain){
        List<PhoneCardVo> phoneCardList = this.transferPhoneMapper.getPhoneCardListPlus(orderMain);
        if (CollectionUtil.isEmpty(phoneCardList)) {
            return ListUtil.empty();
        }
        //根据手机编码进行分组
        Map<String, List<PhoneCardVo>> phoneGroup =
                phoneCardList.stream().collect(Collectors.groupingBy(PhoneCardVo::getPhoneCode));
        List<PhoneCardVo> results = new ArrayList<>();
        for (Map.Entry<String, List<PhoneCardVo>> entry : phoneGroup.entrySet()) {
            PhoneCardVo phoneCardVo = new PhoneCardVo();
            phoneCardVo.setPhoneCode(entry.getKey());
            if (CollectionUtil.isNotEmpty(entry.getValue())) {
                phoneCardVo.setPhoneCodeColor(CollectionUtil.getFirst(entry.getValue()).getPhoneCodeColor());
                phoneCardVo.setOrderNumber(CollectionUtil.getFirst(entry.getValue()).getOrderNumber());
                phoneCardVo.setPhoneNo(CollectionUtil.getFirst(entry.getValue()).getPhoneNo());
                phoneCardVo.setPhoneNoColor(CollectionUtil.getFirst(entry.getValue()).getPhoneNoColor());
                phoneCardVo.setNameList(entry.getValue().stream().map(PhoneCardVo::getCustomName).collect(Collectors.toList()));
                Collections.sort(phoneCardVo.getNameList(), Comparator.comparingInt(String::length));

            }
            results.add(phoneCardVo);
        }
        //对List进行排序,根据对象中的orderNumber字段进行排序.
        results.sort(Comparator.comparingDouble(o ->
                {
                    if (StrUtil.isEmpty(o.getOrderNumber())){
                        return Double.MAX_VALUE;
                    }else{
                        return Double.parseDouble(o.getOrderNumber());
                    }
                }
        ));
        return results;
    }

    public String getPhoneUseMemo() {
        TransferPhone transferPhone = this.transferPhoneMapper.getPhoneUseMemo();
        return transferPhone.getMemo();
    }

    public void updatePhoneUseMemo(TransferPhone phoneUseMemo) {
        this.transferPhoneMapper.updatePhoneUseMemo(phoneUseMemo.getMemo());
    }
}
